import eventBus from './eventBus.js'
import stores from '@/stores'
const store = stores
const ctrlKey = 17,
  commandKey = 91,
  altKey = 18,
  shiftKey = 16,
  vKey = 86, // 粘贴
  cKey = 67, // 复制
  xKey = 88, // 剪切
  yKey = 89, // 重做
  zKey = 90, // 撤销
  gKey = 71, // 组合
  bKey = 66, // 拆分
  lKey = 76, // 锁定
  uKey = 85, // 解锁
  sKey = 83, // 保存
  pKey = 80, // 预览
  dKey = 68, // 删除
  deleteKey = 46 // 删除

export const keycodes = [66, 67, 68, 69, 71, 76, 80, 83, 85, 86, 88, 89, 90]
//与组件状态无关的操作
const basemap = {
  [vKey]: paste,
  [yKey]: redo,
  [zKey]: undo,
  //[sKey]: save,
  // [pKey]: preview,
  // [eKey]: clearCanvas,
}
// 组件锁定状态下可以执行的操作
const lockMap = {
  ...basemap,
  [uKey]: unlock,
}

// 组件未锁定状态下可以执行的操作
const unlockMap = {
  ...basemap,
  [cKey]: copy,
  [xKey]: cut,
  // [gKey]: compose,
  // [bKey]: decompose,
  [dKey]: deleteComponent,
  [deleteKey]: deleteComponent,
  [lKey]: lock,
}

let isCtrlOrCommandDown = false

//全局监听按键操作并执行相应命令
export const listenGlobalKeyDown = () => {
  window.onkeydown = (e) => {
    if (!store.state.printTemplateModule.isInEditor) return;
    const {curComponent} = store.state.printTemplateModule
    const { keyCode } = e
    if (keyCode === ctrlKey || keyCode === commandKey) {
      isCtrlOrCommandDown = true
    }else if(keyCode === deleteKey && curComponent) {
      store.commit('printTemplateModule/deleteComponent')
      store.commit('printTemplateModule/recordSnapshot')
    }else if(isCtrlOrCommandDown && keycodes.includes(keyCode)) {
      if(unlockMap[keyCode] && (!curComponent || !curComponent.isLock) ) {
        e.preventDefault()
        unlockMap[keyCode]()
      }else if(lockMap[keyCode] && curComponent && curComponent.isLock) {
        e.preventDefault()
        lockMap[keyCode]()
      }
    }
  }
  window.onkeyup = (e) => {
    if(e.keyCode === ctrlKey || e.keyCode === commandKey) {
      isCtrlOrCommandDown = false
    }
  }
  window.onmousedown = ()=>{
    store.commit('printTemplateModule/setInEditorStatus',false)
  }
}

function copy() {
  store.commit('printTemplateModule/copy')
}
function paste() {
  store.commit('printTemplateModule/paste')
  store.commit('printTemplateModule/recordSnapshot')
}
function cut() {
  store.commit('printTemplateModule/cut')
}
function redo() {
  store.commit('printTemplateModule/redo')
}
function undo() {
  store.commit('printTemplateModule/undo')
}
function lock() {
  store.commit('printTemplateModule/lock')
}
function unlock() {
  store.commit('printTemplateModule/unlock')
}
function deleteComponent() {
  if (store.state.printTemplateModule.curComponent) {
    store.commit('printTemplateModule/deleteComponent')
    store.commit('printTemplateModule/recordSnapshot')
  }
}
